﻿using Rainbow.model;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Rainbow.common.comparer
{
    /// <summary>
    /// 文件名排序
    /// </summary>
    public class NaturalFileInfoViewModelComparer : IComparer<FileInfoViewModel>
    {
        private static readonly Regex _regex = new Regex(@"(\d+|\D+)", RegexOptions.Compiled);

        public int Compare(FileInfoViewModel x, FileInfoViewModel y)
        {
            if (x == null || y == null)
                return 0;

            string nameX = x.Name;
            string nameY = y.Name;

            var matchesX = _regex.Matches(nameX);
            var matchesY = _regex.Matches(nameY);

            for (int i = 0; i < Math.Min(matchesX.Count, matchesY.Count); i++)
            {
                string partX = matchesX[i].Value;
                string partY = matchesY[i].Value;

                int numberX, numberY;
                bool isNumberX = int.TryParse(partX, out numberX);
                bool isNumberY = int.TryParse(partY, out numberY);

                int result;
                if (isNumberX && isNumberY)
                {
                    result = numberX.CompareTo(numberY);
                }
                else
                {
                    result = string.CompareOrdinal(partX, partY);
                }

                if (result != 0)
                    return result;
            }

            return matchesX.Count.CompareTo(matchesY.Count);
        }
    }
}
